package com.leigq.basaltools.util;

import com.leigq.basaltools.bean.Response;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.util.Assert;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;

/**
 * WebUtils，Web环境下使用，直接在 Main 方法中使用无效
 *
 * @author leigq
 */
@Slf4j
public abstract class WebUtils extends org.springframework.web.util.WebUtils {

    /**
     * Gets HttpServletRequest.
     *
     * @return the request
     */
    public static HttpServletRequest getRequest() {
        return getRequestAttributes().getRequest();
    }


    /**
     * Gets HttpServletResponse.
     *
     * @return the response
     */
    public static HttpServletResponse getResponse() {
        return getRequestAttributes().getResponse();
    }

    /**
     * Gets HttpSession.
     *
     * @return the session
     */
    public static HttpSession getSession() {
        return getRequest().getSession();
    }

    /**
     * Gets Cookies.
     *
     * @return the session
     */
    public static Cookie[] getCookies() {
        return getRequest().getCookies();
    }

    /**
     * Gets header.
     *
     * @param name the name
     * @return the header
     */
    public static String getHeader(String name) {
        return getRequest().getHeader(name);
    }

    /**
     * Gets User-Agent
     */
    public static String getUserAgent() {
        return getRequest().getHeader("User-Agent");
    }


    /**
     * 将错误信息以 json 格式输出到 Response（前端）, 默认错误码
     * <br/>
     * 适用于 Controller、Service 层业务流程执行、判断，事务不需要回滚，无返回值的方法。例如：Excel、Word文档导出
     * <br/>
     * 调用下面的方法之后，必须手动 return; 不然后面的代码会继续执行
     *
     * @param errorMsg 错误信息
     */
    public static void writeError(String errorMsg) {
        writeResponse(Response.fail(errorMsg));
    }


    /**
     * 将 Response 以 json 格式输出到 Response（前端）
     * <br/>
     * 适用于 Controller、Service 层业务流程执行、判断，事务不需要回滚，无返回值的方法。例如：Excel、Word文档导出
     * <br/>
     * 调用下面的方法之后，必须手动 return; 不然后面的代码会继续执行
     *
     * @param response the response
     */
    public static <T> void writeResponse(Response<T> response) {
        HttpServletResponse httpServletResponse = getResponse();
        Assert.notNull(httpServletResponse, "httpServletResponse is null");

        httpServletResponse.setContentType(MediaType.APPLICATION_JSON_VALUE);
        httpServletResponse.setCharacterEncoding(StandardCharsets.UTF_8.name());

        try (PrintWriter writer = httpServletResponse.getWriter()) {
            writer.write(JacksonUtils.toJson(response));
        } catch (IOException e) {
            log.error("将 Response 以 json 格式输出到 Response 异常", e);
        }
    }


    /**
     * 判断是否为 ajax 请求
     *
     * @return the boolean
     */
    public static boolean isAjaxRequest() {
        // 判断是否为ajax请求，默认不是
        boolean isAjaxRequest = false;
        if ("XMLHttpRequest".equalsIgnoreCase(getRequest().getHeader("x-requested-with"))) {
            isAjaxRequest = true;
        }
        return isAjaxRequest;
    }


    /**
     * Gets ServletRequestAttributes.
     *
     * @return the request attributes
     */
    public static ServletRequestAttributes getRequestAttributes() {
        return (ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes());
    }

}
